/*
 *  shmemorytracker.cpp
 *  shaderz_v3
 *
 *  Created by Anjali on 3/23/11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "shmemorytracker.h"
#include "shobject.h"
#include <iostream>

using namespace shaderz;

shMemoryTracker gMemTracker;

std::map<void*, shMemoryTracker::MemAllocInfo>	shMemoryTracker::mAllocationRecords;

shMemoryTracker::~shMemoryTracker()
{
	if( mAllocationRecords.size() > 0 )
	{
		std::cout<<"Memory leak detected.\n";
	
		// todo: try to free upmemeory
		
/*
		std::map<void*, shMemoryTracker::MemAllocInfo>::iterator	leakItr;
		while( mAllocationRecords.size() > 0 )
		{
			leakItr = mAllocationRecords.begin();
			std::cout<<"Freeing up memory: "<<leakItr->first;
			
			const MemAllocInfo& allocInfo = leakItr->second;
			if( allocInfo.isArray )
			{
				std::cout<<" [A]";
				shObject* memToFree = static_cast<shObject*>(leakItr->first);
				delete[] memToFree;
			}
			else
			{
				shObject* memToFree = static_cast<shObject*>(leakItr->first);
				delete memToFree;
			}
			
			std::cout<<std::endl;
		}
*/
	}
}

void shMemoryTracker::registerMemoryAllocation( shObject* InMemory, size_t InSizeInBytes, bool InIsArray, std::string InFileName, int InLineNumber )
{
	// record the allocation
	MemAllocInfo allocInfo;
	allocInfo.sizeInBytes = InSizeInBytes;
	allocInfo.isArray = InIsArray;
	allocInfo.fileName = InFileName;
	allocInfo.lineNumber = InLineNumber;
	
	mAllocationRecords[InMemory] = allocInfo;
}

void shMemoryTracker::unRegisterMemoryAllocation( shObject* InObjectToFree )
{
	mAllocationRecords.erase(InObjectToFree);
}